package org.yanghaokun.product.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yanghaokun.basic.service.impl.BaseServiceImpl;
import org.yanghaokun.product.domain.Product;
import org.yanghaokun.product.domain.ProductDetail;
import org.yanghaokun.product.mapper.ProductDetailMapper;
import org.yanghaokun.product.mapper.ProductMapper;
import org.yanghaokun.product.service.IProductService;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductDetailMapper productDetailMapper;

    /**
     * 联表查询
     * @param id
     */
    @Override
    public void del(Long id) {
        //链表删除，把自己删除之后还要删除产品详情
        productMapper.delete(id);
        //删除详情
        productDetailMapper.delByproductId(id);
    }

    /**
     * 我们直接整合细节得查询在这里方便
     * @param productId
     * @return
     */
    @Override
    public ProductDetail findOneDetail(Long productId) {
        return productDetailMapper.findByproductId(productId);
    }

    @Override
    public void onsaleOrOffsale(int flag, List<Long> ids) {
        if (flag == 1) {
            Map<String, Object> result = new HashMap<>();
            result.put("onsaletime",new Date());
            result.put("ids",ids);
            productMapper.onsale(result);
        }else if (flag == 0){
            Map<String, Object> result = new HashMap<>();
            result.put("offsaletime",new Date());
            result.put("ids",ids);
            productMapper.offSale(result);
        }
    }

    @Override
    public void bulkDel(List<Long> ids) {
        productMapper.bulkDel(ids);
        productDetailMapper.bulkDel(ids);
    }


    @Override
    public void update(Product product) {
        productMapper.update(product);
        //联表更该，我们要从服务里面获取到当前服务的服务详情
        ProductDetail detail = product.getDetail();
        //做一个非空判断，如果查到了又有i的说明有详情可以更改
        if (detail != null) {
            if (detail.getId() != null) {
                productDetailMapper.update(detail);
            }else {//否则就是当前服务没有详情只能做添加
                productDetailMapper.save(detail);
            }
        }
    }

    @Override
    public void add(Product product) {
        //先添加本身
        productMapper.save(product);
        ProductDetail detail = product.getDetail();
        //detail不为空才能保存不然空异常（我在测试的过程中已经遇到这个bug了找了老半天）
        if (detail != null) {
            //两边表关联起来
            detail.setProduct_id(product.getId());
            productDetailMapper.save(detail);
        }
    }
}
